# 股票一日数据
from time import sleep

import akshare as ak
import os
import sqlite3
from datacache import table_exists
import pandas as pd
from datetime import datetime

conn = sqlite3.connect(os.path.join(os.getcwd(), 'stock_day_data_cache.db'), check_same_thread=False)

def get_stock_day_detail_data(stock_code, date):
    formatted_date = datetime.strptime(date, "%Y%m%d").strftime('%Y-%m-%d')
    # date 格式 2020-01-01
    start_date: str = f"{formatted_date} 09:30:00"
    end_date: str = f"{formatted_date} 15:00:00"
    period: str = "5"
    df = ak.stock_zh_a_hist_min_em(symbol=stock_code, start_date=start_date, end_date=end_date, period=period)
    if not df.empty:
        table_name = f'stock_{stock_code}_day_{date}'
        # 目标表已存在，则替换
        df.to_sql(table_name, conn, if_exists='replace', index=False)
        print(f"Data for {stock_code} cached in table '{table_name}'.")

def get_stock_day_data(stock_code, date):
    table_name = f'stock_{stock_code}_day_{date}'
    is_table_exist = table_exists(table_name)
    if not is_table_exist:
        get_stock_day_detail_data(stock_code, date)
        sleep(2)
    try:
        # 连接到 SQLite 数据库
        query = f"""
        SELECT *
        FROM {table_name}
        """
        # 使用 pandas 读取 SQL 查询结果
        df = pd.read_sql_query(query, conn)
        return df
    except sqlite3.OperationalError:
        print(f"No cached data found for symbol {stock_code}.")
        return None

if __name__ == '__main__':
    stock_code="000001"
    stock_date="20250206"
    get_stock_day_data(stock_code, stock_date)
